package org.calrissian.restdoclet.model.type.property;

import com.sun.javadoc.FieldDoc;
import com.sun.javadoc.RootDoc;
import com.sun.javadoc.Type;
import org.calrissian.restdoclet.model.Model;
import org.calrissian.restdoclet.model.ModelProperty;
import org.calrissian.restdoclet.model.type.ParamTypeInfo;
import org.calrissian.restdoclet.model.type.ParamTypeInfos;
import org.calrissian.restdoclet.util.TypeUtils;

import java.util.Map;

import static org.calrissian.restdoclet.util.TypeUtils.*;

/**
 * 这时纯泛型字段的处理器
 * Created by admin on 2017/9/3.
 */
public class TypeVairableModelPropertyGentor extends ModelPropertyGenerator{

    @Override
    public boolean belongToThisGenerator(Type fieldType, Type ownerType) {
        if (null != fieldType.asTypeVariable() && null != ownerType.asParameterizedType()) {
            return true;
        }
        return false;
    }

    @Override
    public ModelProperty generate(Type fieldType, FieldDoc fieldDoc, Type ownerType, Map<String, Model> result, RootDoc rootDoc, ParamTypeInfos paramTypeInfos) {

        ModelProperty modelProperty = getBaseModelProperty(fieldType, fieldDoc);

        ParamTypeInfo paramTypeInfo = paramTypeInfos.get(ownerType.toString());
        Type cascadeLoadType = fieldType;
        if(paramTypeInfo != null) {
            Type paramType = paramTypeInfo.getParamType(fieldType.qualifiedTypeName());
            cascadeLoadType = paramType;
            fieldType = paramType;
        }

        if(TypeUtils.dataType(fieldType).startsWith("array")) {
            modelProperty = new ArrayModelPropertyGentor().generate(fieldType, fieldDoc, ownerType, result, rootDoc, paramTypeInfos);
        } else {
            if (needLoad(cascadeLoadType)
                    && !result.containsKey(dataType(cascadeLoadType))) {
                result.putAll(getModel(result, cascadeLoadType, rootDoc, getAllParamTypeInfos(cascadeLoadType, paramTypeInfos)));
            }
            modelProperty.setType(dataType(fieldType));
        }

        return modelProperty;
    }
}
